package org.demo.filemanager.widget.filesystem;

import java.awt.event.MouseEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.boxlayout.gui.BoxLayoutEngine;
import org.boxlayout.gui.MouseCustomable;
import org.boxlayout.gui.VisualElement;
import org.boxlayout.gui.layout.LayoutFactory;
import org.boxlayout.gui.type.ColorEnum;
import org.boxlayout.gui.widget.TreeBrowsable;

public class DirectoryFileWidget extends FileWidget {

	List<TreeBrowsable> fileWidgetChilds = new ArrayList<TreeBrowsable>();
	
	public DirectoryFileWidget(BoxLayoutEngine ble, String path) {
		super(ble, path);
	}

	public TreeBrowsable initVisual() {
		defaultColor = ColorEnum.YELLOW;
		super.initVisual();
		this.nameContainer.setMouseReleasedListener(new MouseCustomable() {
			public void onEvent(MouseEvent event) {
				System.out.println("folderOpen");
				setExpanded(!expanded);
				if(expanded){
					me.focus();					
				}else{
					TreeBrowsable parent = me.getParent();
					if(parent!=null)parent.focus();
				}
				//selector.select(me);
			}
		});
		return this;
	}

	public void setExpanded(Boolean expend) {
		if (!expanded && expend) {
			retrieveChilds();
			childLayout.setEnable(true);
			ble.reLayout();			
			childLayout.scaleIn();
		} else if (expanded && !expend) {
			childLayout.setEnable(false);
			ble.reLayout();
			childLayout.scaleOut();
		}		
		expanded = expend;
	}

	protected void retrieveChilds() {
		File file = new File(path);
		File[] childFiles = file.listFiles();
		fileWidgetChilds.clear();
		childContainer = ble.createElement()
		// Childs
				.setLayout(LayoutFactory.getInstance().getVerticalLayout()).setPadding(padding).setColor(
						ColorEnum.WHITE);

		for (int i = 0; i < childFiles.length; i++) {
			File childFile = childFiles[i];
			TreeBrowsable newChildFileWidget;
			try {
				newChildFileWidget = FileWidgetFactory.getInstance()
						.createFileWidget(childFile.getAbsolutePath());
				fileWidgetChilds.add(newChildFileWidget);
				newChildFileWidget.setParent(this);
				childContainer.add(newChildFileWidget.getVisual());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		VisualElement newChildLayout = ble.createElement()
			.setLayout(LayoutFactory.getInstance().getHorizontalLayout())
			.setPadding(padding).setColor(ColorEnum.WHITE)
			.add(// blank
				ble.createElement()
				.setLayout(LayoutFactory.getInstance().getFloatingLayout())
				.setColor(ColorEnum.WHITE)
				.setPadding(padding)
				.setPreferedWidth(0.1f).setHeight(0.0f)
			)
			.add(childContainer);

		if (childLayout == null) {
			visual.add(newChildLayout);
		} else {
			visual.replace(childLayout, newChildLayout);
		}
		childLayout = newChildLayout;

	}

	public List<TreeBrowsable> getChilds(){
		return fileWidgetChilds;
	}
	
}
